package com.ycl.orderservice.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ycl.orderservice.client.ProductFeignClient;
import com.ycl.orderservice.entity.Order;
import com.ycl.orderservice.entity.PageVO;
import com.ycl.orderservice.entity.Product;
import com.ycl.orderservice.service.OrderService;

import jakarta.annotation.Resource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class OrderController {

    @Resource
    private OrderService orderService;

    @Resource
    private ProductFeignClient productFeignClient;

    @SentinelResource(value = "order/{id}",fallback = "orderFallback",blockHandlerClass = MyBlockHandler.class)

    @GetMapping("/order/{id}")
    public ResponseEntity<Order> findOrderById(@PathVariable Integer id){
        //查询订单
        Order order = orderService.getById(id);
        //通过feign调用商品服务
        ResponseEntity<Product> entity =
                productFeignClient.findProductById(order.getProductId());
        //设置订单的商品对象
        order.setProduct(entity.getBody());
        return ResponseEntity.ok(order);
    }
    @GetMapping("/orders")
    public ResponseEntity<List<Order>> findAllOrders(){
        List<Order> list = orderService.list();
        return ResponseEntity.ok(list);
    }

    @GetMapping("/orders-page")
    public ResponseEntity<PageVO> findOrdersPage(
    @RequestParam(value = "current",required = false,defaultValue = "1") Integer current,
    @RequestParam(value = "pageSize",required = false,defaultValue = "10") Integer pageSize){
        Page<Order> page = orderService.page(new Page<>(current, pageSize));
        PageVO pageVO = new PageVO(current,pageSize,page.getTotal(),page.getRecords());
        return ResponseEntity.ok(pageVO);
    }
    @PostMapping("/order")
    public ResponseEntity<String> addProduct(@RequestBody Order order){
        orderService.save(order);
        return ResponseEntity.ok("OK");
    }

    @PutMapping("/order")
    public ResponseEntity<String> updateProduct(@RequestBody Order order){
        orderService.updateById(order);
        return ResponseEntity.ok("OK");
    }

    @DeleteMapping("/order/{id}")
    public ResponseEntity<String> deleteOrder(@PathVariable Integer id){
        orderService.removeById(id);
        return ResponseEntity.ok("OK");
    }

}
